//
//  MKAPIDictionary.m
//  MKAPI
//
//  Created by 苏尚进 on 2022/8/26.
//  Copyright © 2022 moon. All rights reserved.
//

#import "MKAPIDictionary.h"
#import "MKAPIPreCompile.h"
#import "NSObject+MKAPI.h"

@interface MKAPIDictionary()
@property(nonatomic,strong) NSMutableDictionary *params;
@property(nonatomic,strong) MKAPIDictionaryBlock P;//设置参数
@property(nonatomic,strong) MKAPIDictionaryBlockS PS;//设置参数
@end

@implementation MKAPIDictionary
- (id)initWithDictionary:(NSDictionary<NSString *,id> *)dictionary{
    if (self=[self init]) {
        [self addDictionary:dictionary];
    }
    return self;
}
- (id)init{
    if (self=[super init]) {
        self.params = [[NSMutableDictionary alloc] init];
        @MKAPI_WEAKIFY(self);
        self.P = ^MKAPIDictionary *(NSString *k,id _Nullable v){
            @MKAPI_NORMALIZE(self);
            [self.params mkapi_setObject:v forKeyPath:k];
            return self;
        };
        self.PS = ^MKAPIDictionary *(NSDictionary *_Nullable v){
            @MKAPI_NORMALIZE(self);
            [self.params addEntriesFromDictionary:v];
            return self;
        };
    }
    return self;
}
- (NSUInteger)count{
    return _params.count;
}
+ (MKAPIDictionaryBlock)P{
    return ^MKAPIDictionary *(NSString *k,id _Nullable v){
        MKAPIDictionary *params = [[MKAPIDictionary alloc] init];
        return params.P(k,v);
    };
}
+ (MKAPIDictionaryBlockS)PS{
    return ^MKAPIDictionary *(NSDictionary *_Nullable v){
        MKAPIDictionary *params = [[MKAPIDictionary alloc] init];
        return params.PS(v);
    };
}
- (id)copyWithZone:(nullable NSZone *)zone{
    MKAPIDictionary *obj = [[self.class alloc] init];
    [obj addDictionary:self.dictionary];
    return obj;
}
- (NSString *)description{
    return [NSString stringWithFormat:@"<%@:%p,dictionary:%@>",NSStringFromClass(self.class),self,self.params];
}
- (NSDictionary *)dictionary{
    return [self.params copy];
}
- (nullable id)objectForKeyedSubscript:(id)key{
    return [self.params valueForKeyPath:key];
}
- (void)setObject:(nullable id)obj forKeyedSubscript:(id)key{
    [self.params mkapi_setObject:obj forKeyPath:key];
}
- (void)addDictionary:(NSDictionary *)dictionaryParam{
    [self.params addEntriesFromDictionary:dictionaryParam];
}
- (void)removeAll{
    [self.params removeAllObjects];
}
@end


@implementation MKAPIDictionary(KeyValueUrlEncode)
- (NSString *)keyValuesUrlEncodeString{
    NSString *result = self.dictionary.mkapi_keyValuesUrlEncode;
    return result;
}
@end
@implementation MKAPIDictionary(NSMutableURLRequest)
- (void)setHTTPHeaderFieldToRequest:(NSMutableURLRequest *)request{
    if(!request)return;
    NSDictionary *dictionary = self.dictionary;
    for (NSString *k in dictionary) {
        NSString *v = [dictionary[k] description];
        [request setValue:v forHTTPHeaderField:k];
    }
}
@end
